/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.acq.service.breedtype;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.service.TreeService;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.acq.entity.breedtype.AcqBreedType;
import com.thinkgem.jeesite.modules.acq.dao.breedtype.AcqBreedTypeDao;

/**
 * 养殖品类表Service
 * @author lj
 * @version 2018-04-13
 */
@Service
@Transactional(readOnly = true)
public class AcqBreedTypeService extends TreeService<AcqBreedTypeDao, AcqBreedType> {

	public AcqBreedType get(String id) {
		return super.get(id);
	}
	
	public List<AcqBreedType> findList(AcqBreedType acqBreedType) {
		if (StringUtils.isNotBlank(acqBreedType.getParentIds())){
			acqBreedType.setParentIds(","+acqBreedType.getParentIds()+",");
		}
		return super.findList(acqBreedType);
	}
	
	@Transactional(readOnly = false)
	public void save(AcqBreedType acqBreedType) {
		CacheUtils.remove("breedjson");
		super.save(acqBreedType);
	}
	
	@Transactional(readOnly = false)
	public void delete(AcqBreedType acqBreedType) {
		super.delete(acqBreedType);
	}
	
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = false)
	public Map<String,Object> breedjson() {
		Map<String,Object> result = new HashMap<String,Object>();
		try{
			Object breedjson = CacheUtils.get("breedjson");
			if(breedjson!=null){
				result.put("data", (List<Map<String,Object>>)breedjson);
				result.put("success", true);
				result.put("msg", "success");
				return result;
			}
			//1.查询所有顶级
			List<Map<String,Object>> top = dao.topbreedjson();
			List<Map<String,Object>> list = getBreedJson(top);
			result.put("data", list);
			result.put("success", true);
			result.put("msg", "success");
			CacheUtils.put("breedjson", list);
			return result;
		}catch(Exception e){
			e.printStackTrace();
			result.put("status", false);
			result.put("msg", "faild");
			return result;
		}
		
		
	}
	
	//递归算法查询子级	
	public List<Map<String,Object>> getBreedJson(List<Map<String,Object>> list){
		for(int i=0;i<list.size();i++){
			List<Map<String,Object>> child = dao.childbreedjson((String)list.get(i).get("value"));
			if(child.size()>0){
				list.get(i).put("children", child);
				getBreedJson(child);
			}
			
		}
		return list;		
	}
	
}